﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.Core.Snowflake;
using ZilLion.Service.ZilLionOss.Domain.Entitys;
using ZilLion.Service.ZilLionOss.Domain.Repositorys.Interface;

namespace ZilLion.Service.ZilLionOss.Domain.Repositorys
{
    public class OssRoleRepository : SqlServerRespository<OssRoleEntity>, IOssRoleRepository
    {
        public OssRoleRepository()
        {
            Context = new OssContext();
        }


        public OssRoleEntity GetOssRoleById(long roleid)
        {
            return
                GetList("select RoleId ,RoleName  ,RoleDesc from oss_role where roleid=@roleid", new {roleid})
                    .FirstOrDefault();
        }

        public OssRoleEntity SaveOssRole(OssRoleEntity entity)
        {
            if (GetOssRoleById(entity.RoleId) != null && entity.RoleId > 0)
            {
                Modify(entity);
            }

            else
            {
                var id = SnowflakeIdCreater.Instance().GetNextId();
                entity.RoleId = id;
                Add(entity);
            }

            return GetOssRoleById(entity.RoleId);
        }


        public IEnumerable<OssRoleEntity> GetOssUserRoles(long userid)
        {
            return
                GetList($@"SELECT  a.roleid as RoleId,
                        a.rolename as RoleName,
                        a.roledesc as RoleDesc
                        FROM oss_role a
                        INNER JOIN oss_user_roles b ON a.roleid = b.roleid  where b.userid =@userid",
                    new {userid});
        }

        public IEnumerable<OssRoleEntity> GetAllRoles()
        {
            return GetAll();
        }

        public void DeleteRole(long roleid, UnitOfWork unit = null)
        {
            var entity = GetOssRoleById(roleid);
            if (entity != null)
                Remove(entity, unit);
        }
    }
}